package zl.ordermanager.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import zl.ordermanager.service.DriverService;
import zl.ordermanager.vo.DataGrid;
import zl.ordermanager.vo.Driver;
import zl.ordermanager.vo.PageHelper;

@Controller
@RequestMapping("/driver")
public class DriverController extends BaseController {

	@Autowired
	private DriverService driverService;
	
	@RequestMapping("/showList")
	public String showList(PageHelper pageHelper, Model model) {
		DataGrid<Driver> dataGrid = driverService.dataGrid(pageHelper);
		List<Driver> driverList = dataGrid.getList();
		long totalCount = dataGrid.getTotal();

		model.addAttribute("driverList", driverList);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageHelper", pageHelper);

		return "driverList";
	}

	@RequestMapping("/showAdd")
	public String showAdd(Model model) {
		return "driverAdd";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public ModelAndView add(Driver driver) {
		try {
			driverService.add(driver);
		} catch (Exception e) {
			return ajaxDoneError(e.getMessage());
		}

		return ajaxDoneSuccess("操作成功");
	}

	@RequestMapping("/showEdit/{driverId}")
	public String showEdit(@PathVariable("driverId") Integer driverId, Model model) {
		Driver driver = driverService.get(driverId);

		model.addAttribute("driver", driver);

		return "driverEdit";
	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public ModelAndView edit(Driver driver) {
		try {
			driverService.edit(driver);
		} catch (Exception e) {
			return ajaxDoneError(e.getMessage());
		}
		return ajaxDoneSuccess("操作成功");
	}

	@RequestMapping("/delete/{driverId}")
	public ModelAndView delete(@PathVariable("driverId") Integer driverId) {

		driverService.delete(driverId);

		return ajaxDoneSuccess("操作成功");
	}
}
